<?php

namespace app\admin\service\user_profile\userArchive;

use app\admin\service\UserService;
use app\common\Message;
use app\model\archives_model\UserArchiveModel;
use app\model\ConsultOfflineModel;
use app\model\ConsultOnlineModel;
use app\model\DepartmentAdminModel;
use app\model\DepartmentLevelModel;
use app\model\DepartmentModel;
use app\model\FollowUserModel;
use app\model\InterfereUserModel;
use app\model\not_del\DepartmentModel as NotDelDepartmentModel;
use app\model\ProxyEvaluationResultModel;
use app\model\SelfEvaluationResultModel;
use app\model\TaskUserModel;
use app\model\TaskUserResultModel;
use app\model\user_profile_model\UserProfileRecode;
use app\model\UserModel;
use app\model\WarningReportRecordModel;
use think\App;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Service;

class UserArchiveService extends Service
{
    use Message;

    /**
     * @throws DbException
     */
    public function getList($data): bool
    {
        $where = [
            ['unit_id','=',$data['unit_id']],
            ['role_mode','=',3],
        ];
        /*搜索条件-开始*/
        $searchKey = ['username','name','sex','student_status','department_id','mode'];
        foreach ($searchKey as $v) {
            if (check_array_key($v, $data)){
                switch ($v){
                    case 'username':
                    case 'name':
                        $where[] = ['name|username', 'like', '%' . $data[$v] . '%'];
                        break;
                    case 'sex':
                        if($data[$v] != 0){
                            $where[] = ['sex', '=', $data[$v]];
                        }
                        break;
                    case 'student_status':
                        if($data[$v] != 0){
                            $where[] = ['student_status', '=', $data[$v]];
                        }
                        break;
                    case 'department_id':
                        $DepartmentModel = new NotDelDepartmentModel();
                        $DepartmentList = $DepartmentModel->field('id,pid')
                            ->where(['unit_id' => $data['unit_id']])->select()->toArray();
                        $getAllSubcategories = getAllSubcategories($DepartmentList,$data[$v]);
                        $ids = array_column($getAllSubcategories, 'id');
                        $ids[] = $data[$v];
                        $where[] = ['department_id', 'in', $ids];
                        break;
                    case 'mode':
                        //搜索用户所属学制
                        $level = new DepartmentModel();
                        $Department_ids = $level->where([
                            ['unit_id','=',$data['unit_id']],
                            ['mode','=',$data[$v]]
                        ])->column('id');
                        if (count($Department_ids)>0){
                            $where[] = ['department_id', 'in', $Department_ids];
                        }else{
                            $where[] = ['id', '=', -1];
                        }
                        break;
                }
            }
        }
        if (!empty($data['other_record_id'])){
            $uids = [];
            foreach ($data['other_record_id'] as $value) {
                switch ($value){
                    case 1:
                        $InterfereUserModel = new InterfereUserModel();
                        $uid = $InterfereUserModel->where('unit_id','=',$data['unit_id'])->column('uid');
                        break;
                    case 2:
                        $FollowUserModel = new FollowUserModel();
                        $uid = $FollowUserModel->where('unit_id','=',$data['unit_id'])->column('uid');
                        break;
                    case 3:
                        $WarningReportRecordModel = new WarningReportRecordModel();
                        $uid = $WarningReportRecordModel->where('unit_id','=',$data['unit_id'])->column('uid');
                        break;
                    case 4:
                        $ConsultOnlineModel = new ConsultOnlineModel();
                        $uid = $ConsultOnlineModel->where('unit_id','=',$data['unit_id'])->column('uid');
                        break;
                    case 5:
                        $ConsultOfflineModel = new ConsultOfflineModel();
                        $uid = $ConsultOfflineModel->where('unit_id','=',$data['unit_id'])->column('uid');
                        break;
                    default:
                        break;
                }
                if (count($uid) > 0){
                    if (!empty($uids)){
                        $uids = array_intersect($uids, $uid);
                    }else{
                        $uids = $uid;
                    }
                }
                if (empty($uids)){
                    break;
                }
            }
            if (!empty($uids)){
                $where[] = ['id', 'in', $uids];
            }else{
                $where[] = ['id', '=', -1];
            }
        }
        /*搜索条件-结束*/
//        $where[] = ['is_repeal','=',0];
        $where[] = ['is_normal','=',1];
//        $UserArchiveModel = new UserArchiveModel();
//        $uid = $UserArchiveModel->where([
//            ['unit_id','=',$data['unit_id']],
//            ['is_repeal','=',0]
//        ])->column('user_id');
//        if (count($uid) > 0){
//            $where[] = ['id', 'in', $uid];
//        }else{
//            $where[] = ['id', '=', -1];
//        }
        //njkyl新增需求
//        if ($data['role_mode'] > 0){
//            $DepartmentAdminModel = new DepartmentAdminModel();
//            $department_id = $DepartmentAdminModel->where('uid','=',$data['uid'])->distinct(true)->column('department_id');
//            if (!empty($department_id)){
//                $where[] = ['department_id', 'in', $department_id];
//            }else{
//                $where[] = ['id','=',-1];
//            }
//        }

        $field = ['id,name,username,avatar,sex,province_name,age,phone,nation,city_name,area_name,department_id,unit_id,
        user_number,archive_update_time,time,student_status'];
        $list = UserModel::query()->where($where)->with(['departmentNameMode','unitName'])->field($field)->paginate($data['pageSize'])->toArray();
        if(count($list)>0){
            $UserService = new UserService($this->app);
            $DepartmentAffiliationAll = $UserService->getDepartmentAffiliationAll($data['unit_id']);
            $department_ids = array_column($list['data'], 'department_id');
            $DepartmentAdminAll = $UserService->getDepartmentAdminAll($department_ids);
            foreach ($list['data'] as &$item) {
                if($item['archive_update_time'] == null) $item['archive_update_time'] = $item['time'];
                //所在部门
                $item['department_name'] = $DepartmentAffiliationAll[$item['department_id']]['name']??'';
                //部门管理员
                $item['department_admin'] = $DepartmentAdminAll[$item['department_id']]['user_name']??'';

            }
        }
        $this->result = $list;
        $this->message = '操作成功！';
        return true;
    }

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function getPermission($data)
    {
        $where = [
            ['uid','=',$data['uid']],
            ['is_expire','=',0],
        ];
        $is_expire = UserProfileRecode::query()->where($where)->field('id')->findOrEmpty();
        if ($is_expire->isEmpty()) {
            $this->result = 1;
            $this->message = '暂无权限查阅档案！';
            return true;
        }else{
            $this->result = 0;
            $this->message = '操作成功！';
            return true;
        }
    }

    public function getClass($data)
    {
        $DepartmentModel = new DepartmentModel();
        $data = $DepartmentModel->field('id,pid,name,mode,stage,number')
            ->with('departmentLevel')
            ->where([
                'unit_id' => $data['unit_id'],
            ])->select()->toArray();
        foreach ($data as &$item) {
            $item['level_rules'] = isset($item['level_rules'])?json_decode($item['level_rules'],true):[];
            $item['stage_name'] = $item['level_rules'][$item['stage']] ?? '';
        }
        $this->result = rule_trees($data);
        $this->message = '操作成功！';
        return true;
    }

    //更新数据
    public function updateRepealStatus($model, $where, $update): void
    {
        //删除之前先查询废除档案是否有这个人的档案，有的话先彻底删除废弃档案的数据在废除
        $tempWhere = $where;
        $tempWhere[1] = ['is_repeal','=',1];
        $temp = $model->where($tempWhere)->find();
        if(!empty($temp)){
            //先彻底删除之前的数据
            $model->where($tempWhere)->update(['is_del'=>1]);
        }
        $model->where($where)->update($update);
    }
    public function deleteRecode($data)
    {
        $key = ['type','user_id'];
        foreach($key as $item){
            if(!check_array_key($item,$data)){
                $this->message = '缺少参数！';
                return false;
            }
        }
        if($data['role_mode']>2){
            $this->message = '暂无权限删除！';
            return false;
        }
        switch ($data['type']) {
            case 1:
                // 删除基本信息
                $models = [
                    'UserArchiveModel' => [['user_id', '=', $data['user_id']], ['is_repeal', '=', 0]],
                    'SelfEvaluationResultModel' => [['uid', '=', $data['user_id']], ['is_repeal', '=', 0]],
                    'TaskUserResultModel' => [['uid', '=', $data['user_id']], ['is_repeal', '=', 0]],
                    'ProxyEvaluationResultModel' => [['uid', '=', $data['user_id']], ['is_repeal', '=', 0]],
                    'InterfereUserModel' => [['uid', '=', $data['user_id']], ['is_repeal', '=', 0], ['status', '=', 1]],
                    'ConsultOnlineModel' => [['uid', '=', $data['user_id']], ['is_repeal', '=', 0]],
                    'ConsultOfflineModel' => [['uid', '=', $data['user_id']], ['is_repeal', '=', 0]],
                ];
                //修改用户表is_repeal状态为：已废除。【当有新的资料生成的时候更新状态为未废除，档案查询的就是最新的资料】
                UserModel::query()->where('id',$data['user_id'])->update(['is_normal'=>0]);
                break;
            case 2:
                // 删除个人自评档案
                $models = [
                    'UserArchiveModel' => [['user_id', '=', $data['user_id']], ['is_repeal', '=', 0], ['type_id', '=', 1]],
                ];
                break;
            case 3:
                // 删除测评档案
                $models = [
                    'SelfEvaluationResultModel' => [['uid', '=', $data['user_id']], ['is_repeal', '=', 0]],
                    'TaskUserResultModel' => [['uid', '=', $data['user_id']], ['is_repeal', '=', 0]],
                    'ProxyEvaluationResultModel' => [['uid', '=', $data['user_id']], ['is_repeal', '=', 0]],
                ];
                break;
            case 4:
                // 删除危机干预档案
                $models = [
                    'InterfereUserModel' => [['uid', '=', $data['user_id']], ['is_repeal', '=', 0], ['status', '=', 1]],
                ];
                break;
            case 5:
                // 删除咨询预约档案
                $models = [
                    'ConsultOnlineModel' => [['uid', '=', $data['user_id']], ['is_repeal', '=', 0]],
                    'ConsultOfflineModel' => [['uid', '=', $data['user_id']], ['is_repeal', '=', 0]],
                ];
                break;
        }
        foreach ($models as $modelName => $where) {
            switch ($modelName){
                case 'UserArchiveModel':
                    $model = new UserArchiveModel();
                    break;
                case 'SelfEvaluationResultModel':
                    $model = new SelfEvaluationResultModel();
                    break;
                case 'TaskUserResultModel':
                    $model = new TaskUserResultModel();
                    break;
                case 'ProxyEvaluationResultModel':
                    $model = new ProxyEvaluationResultModel();
                    break;
                case 'InterfereUserModel':
                    $model = new InterfereUserModel();
                    break;
                case 'ConsultOnlineModel':
                    $model = new ConsultOnlineModel();
                    break;
                case 'ConsultOfflineModel':
                    $model = new ConsultOfflineModel();
                    break;
            }
            $update = ['is_repeal' => 1];
            $this->updateRepealStatus($model, $where, $update);
        }
        //修改用户表is_repeal状态为：已废除。【当有新的资料生成的时候更新状态为未废除，档案查询的就是最新的资料】
        UserModel::query()->where('id',$data['user_id'])->update(['is_repeal'=>1,'repeal_time'=>time()]);
        $this->result = 1;
        $this->message = '操作成功！';
        return true;
    }
    //更新数据
    public function updateRepealStatus2($model, $where): int
    {
        //删除之前先查询废除档案是否有这个人的档案，有的话先彻底删除废弃档案的数据在废除
        $temp = $model->where($where)->find();
        if(!empty($temp)){
            //先彻底删除之前的数据
            return 0;
        }else{
            return 1;
        }
    }

    public function checkRepealArchive($data)
    {
        $key = ['type','user_id'];
        foreach($key as $item){
            if(!check_array_key($item,$data)){
                $this->message = '缺少参数！';
                return false;
            }
        }
        if($data['role_mode']>2){
            $this->message = '暂无权限删除！';
            return false;
        }

        switch ($data['type']) {
            case 1:
                // 删除基本信息
                $models = [
                    'UserArchiveModel' => [['user_id', '=', $data['user_id']], ['is_repeal', '=', 1]],
                    'SelfEvaluationResultModel' => [['uid', '=', $data['user_id']], ['is_repeal', '=', 1]],
                    'TaskUserResultModel' => [['uid', '=', $data['user_id']], ['is_repeal', '=', 1]],
                    'ProxyEvaluationResultModel' => [['uid', '=', $data['user_id']], ['is_repeal', '=', 1]],
                    'InterfereUserModel' => [['uid', '=', $data['user_id']], ['is_repeal', '=', 1], ['status', '=', 1]],
                    'ConsultOnlineModel' => [['uid', '=', $data['user_id']], ['is_repeal', '=', 1]],
                    'ConsultOfflineModel' => [['uid', '=', $data['user_id']], ['is_repeal', '=', 1]],
                ];
                break;
            case 2:
                // 删除个人自评档案
                $models = [
                    'UserArchiveModel' => [['user_id', '=', $data['user_id']], ['is_repeal', '=', 1], ['type_id', '=', 1]],
                ];
                break;
            case 3:
                // 删除测评档案
                $models = [
                    'SelfEvaluationResultModel' => [['uid', '=', $data['user_id']], ['is_repeal', '=', 1]],
                    'TaskUserResultModel' => [['uid', '=', $data['user_id']], ['is_repeal', '=', 1]],
                    'ProxyEvaluationResultModel' => [['uid', '=', $data['user_id']], ['is_repeal', '=', 1]],
                ];
                break;
            case 4:
                // 删除危机干预档案
                $models = [
                    'InterfereUserModel' => [['uid', '=', $data['user_id']], ['is_repeal', '=', 1], ['status', '=', 1]],
                ];
                break;
            case 5:
                // 删除咨询预约档案
                $models = [
                    'ConsultOnlineModel' => [['uid', '=', $data['user_id']], ['is_repeal', '=', 1]],
                    'ConsultOfflineModel' => [['uid', '=', $data['user_id']], ['is_repeal', '=', 1]],
                ];
                break;
        }
        foreach ($models as $modelName => $where) {
            switch ($modelName){
                case 'UserArchiveModel':
                    $model = new UserArchiveModel();
                    break;
                case 'SelfEvaluationResultModel':
                    $model = new SelfEvaluationResultModel();
                    break;
                case 'TaskUserResultModel':
                    $model = new TaskUserResultModel();
                    break;
                case 'ProxyEvaluationResultModel':
                    $model = new ProxyEvaluationResultModel();
                    break;
                case 'InterfereUserModel':
                    $model = new InterfereUserModel();
                    break;
                case 'ConsultOnlineModel':
                    $model = new ConsultOnlineModel();
                    break;
                case 'ConsultOfflineModel':
                    $model = new ConsultOfflineModel();
                    break;
            }
            $ret = $this->updateRepealStatus2($model, $where);
            if($ret == 0) break;
        }
        $this->result = $ret;
        $this->message = '操作成功！';
        return true;
    }

    public function checkModelCount($models, $where): int
    {
        $num = 0;
        foreach ($models as $model) {
            $nums = $model->where($where)->count();
            $num += $nums;
        }
        return $num;
    }

    public function isShow($data)
    {
        if(!check_array_key('user_id',$data)){
            $this->message = '缺少参数！';
            return false;
        }
        //模块【1：用户基本信息。2：个人自评档案。3:测评档案。4:危机干预档案，5：咨询预约档案】
        $type = [
            ['id'=>1,'is_show'=>0],//is_show: 0显示。1不显示
            ['id'=>2,'is_show'=>1],
            ['id'=>3,'is_show'=>1],
            ['id'=>4,'is_show'=>1],
            ['id'=>5,'is_show'=>1],
        ];
        $userArchive = new UserArchiveModel();
        if(check_array_key('isAbandon',$data)){
            //废弃档案的数据
            foreach($type as &$item) {
                $where = [];
                switch ($item['id']) {
                    case 1:
                        $where[] = ['user_id','=',$data['user_id']];
                        $where[] = ['is_repeal', '=', 1];
                        $where[] = ['type_id','<>',1];
                        $count = $userArchive->where($where)->count();
                        $item['is_show'] = ($count > 0) ? 0: 1;
                        break;
                    case 2:
                        $where[] = ['user_id','=',$data['user_id']];
                        $where[] = ['type_id','=',1];
                        $where[] = ['is_repeal', '=', 1];
                        $count = $userArchive->where($where)->count();
                        $item['is_show'] = ($count > 0) ? 0: 1;
                        break;
                    case 3:
                        $allModels = [
                            new SelfEvaluationResultModel(), //自我测评
                            new TaskUserResultModel(), //任务测评
                            new ProxyEvaluationResultModel(),//他人测评
                        ];
                        $where[] = ['uid','=',$data['user_id']];
                        $where[] = ['is_repeal', '=', 1];
                        $num = $this->checkModelCount($allModels, $where);
                        $item['is_show'] = ($num > 0) ? 0 : 1;
                        break;
                    case 4:
                        $interfereUser = new InterfereUserModel();
                        $where[] = ['uid','=',$data['user_id']];
                        $where[] = ['status','=',1];
                        $where[] = ['is_repeal', '=', 1];
                        $count = $interfereUser->where($where)->count();
                        $item['is_show'] = ($count > 0) ? 0 : 1;
                        break;
                    case 5:
                        $allModels = [
                            new ConsultOnlineModel(),
                            new ConsultOfflineModel()
                        ];
                        $where[] = ['uid','=',$data['user_id']];
                        $where[] = ['is_repeal', '=', 1];
                        $where[] = ['is_end', '=', 1];
                        $num = $this->checkModelCount($allModels, $where);
                        $item['is_show'] = ($num > 0) ? 0 : 1;
                        break;
                }
            }
        }else{
            //正常档案的数据
            foreach($type as &$item){
                $where = [];
                switch ($item['id']){
                    case 2:
                        $where[] = ['user_id','=',$data['user_id']];
                        $where[] = ['type_id','=',1];
                        $where[] = ['is_repeal', '=', 0];
                        $count = $userArchive->where($where)->count();
                        $item['is_show'] = ($count > 0) ? 0: 1;
                        break;
                    case 3:
                        $allModels = [
                            new SelfEvaluationResultModel(), //自我测评
                            new TaskUserResultModel(), //任务测评
                            new ProxyEvaluationResultModel(),//他人测评
                        ];
                        $where[] = ['uid','=',$data['user_id']];
                        $where[] = ['is_repeal', '=', 0];
                        $num = $this->checkModelCount($allModels, $where);
                        $item['is_show'] = ($num > 0) ? 0 : 1;
                        break;
                    case 4:
                        $interfereUser = new InterfereUserModel();
                        $where[] = ['uid','=',$data['user_id']];
                        $where[] = ['status','=',1];
                        $where[] = ['is_repeal', '=', 0];
                        $count = $interfereUser->where($where)->count();
                        $item['is_show'] = ($count > 0) ? 0 : 1;
                        break;
                    case 5:
                        $allModels = [
                            new ConsultOnlineModel(),
                            new ConsultOfflineModel()
                        ];
                        $where[] = ['uid','=',$data['user_id']];
                        $where[] = ['is_repeal', '=', 0];
                        $where[] = ['is_end', '=', 1];
                        $num = $this->checkModelCount($allModels, $where);
                        $item['is_show'] = ($num > 0) ? 0 : 1;
                        break;
                }
            }
        }
        $this->result = $type;
        $this->message = '操作成功！';
        return true;
    }

}